//
//  CZTabBar.swift
//  CZVVeiBo
//
//  Created by smile on 2017/7/29.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

class CZTabBar: UITabBar {
    
    // 01-声明一个闭包
    var closure:(()->())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 监听事件
    func composeButtonClick(){
        print("composeButtonClick")
        // 03-执行闭包
        closure?()
    }
    
    // MARK: - 设置视图
    func setupUI(){
        addSubview(composeButton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 计算UITabBarButton的宽度
        let w = frame.width * 0.2
        // 索引
        var index: CGFloat = 0
        // UITabBarButton
        // 遍历子控件 控件保存在subviews中
        for view in subviews{
            // 判断是否是UITabBarButton(系统私有类)
            if view.isKind(of: NSClassFromString("UITabBarButton")!) {
//                print(view)
                // 设置UITabBarButton的x轴和宽度
                view.frame.origin.x = index * w
                view.frame.size.width = w
                
                index += 1
//                index = index + 1
                // 给撰写按钮留下位置
                if index == 2 {
                    index += 1
                }
            }
        }
        
        // 设置composeButton 的center
        composeButton.center.x = frame.width * 0.5
        composeButton.center.y = frame.height * 0.5
    }
    
    
    // MARK: - 懒加载控件
    lazy var composeButton: UIButton = {
        let btn = UIButton()
        // 监听事件
        btn.addTarget(self, action: #selector(composeButtonClick), for: UIControlEvents.touchUpInside)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: UIControlState.normal)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: UIControlState.normal)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        // 通过背景图片得到按钮大小
        btn.sizeToFit()
        return btn
    }()

}
